package com.yimi.yinhepda.utils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;

import com.pda.ym.utils.FileUtil;
import com.yimi.yinhepda.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * Created by Administrator on 2016/3/31.
 */
public class UpdateManager {

    private Context context;
    // 返回的安装包url
    private String apkUrl;
    // 下载的文件名
    private static final String saveFileName = "bar-app.apk";
    // messager通知的常量
    private static final int DOWN_UPDATE = 1;
    private static final int DOWN_OVER = 2;
    private static final int UPDATENOTIFY = 3;
    private int progress;
    private Thread downLoadThread;
    private boolean interceptFlag = false;

    private int forceUpdate;
    /* 更新进度条 */
    private ProgressBar mProgress;
    File apkFile;

    public UpdateManager(Context context, String url, int forceUpdate) {
        this.context = context;
        this.apkUrl = url;
        this.forceUpdate = forceUpdate;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATENOTIFY:

                    break;
                case DOWN_UPDATE:
                    mProgress.setProgress(progress);
                    break;
                case DOWN_OVER:
                    installApk();
                    break;
            }
        }
    };

    private void installApk() {
        try {
            if (!apkFile.exists()) {
                return;
            }
            // 通过Intent安装APK文件
            FileUtil fileUtil = new FileUtil(context);
            apkFile = new File(fileUtil.getDownPath() + saveFileName);
            Intent i = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // 4.0以上
                i = new Intent(Intent.ACTION_INSTALL_PACKAGE);
                i.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME, true);
            } else {
                i = new Intent(Intent.ACTION_VIEW);
            }
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.setDataAndType(Uri.fromFile(apkFile),
                    "application/vnd.android.package-archive");
            context.startActivity(i);
            //安装完成后提示完成或者打开
            android.os.Process.killProcess(android.os.Process.myPid());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 外部接口让主Activity调用
    public void checkUpdateInfo() {
        showNoticeDialog();
    }

    /**
     * 显示软件更新对话框
     */
    private void showNoticeDialog() {
        // 构造对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("软件更新");
        builder.setMessage("检测到应用新版本，更新以正常使用");
        builder.setCancelable(false);
        // 更新
        builder.setPositiveButton("确定更新",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // 显示下载对话框
                        showDownloadDialog();
                    }
                });
        if (forceUpdate == 0) {
            // 稍后更新
            builder.setNegativeButton("稍后更新",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            // 退出应用
                            // System.exit(0);
                        }
                    });
        }

        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }

    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog() {
        // 构造软件下载对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("应用下载中...");
        builder.setCancelable(false);
        // 给下载对话框增加进度条
        final LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.softupdate_progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        builder.setView(v);
        // 取消更新
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // 设置取消状态
                interceptFlag = true;
            }
        });
        builder.create().show();
        // 下载文件
        downloadApk();
    }

    private void downloadApk() {
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }

    private Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            URL url;
            try {
                url = new URL(apkUrl);
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream ins = conn.getInputStream();

                FileUtil fileUtil = new FileUtil(context);
                //创建文件前判断文件是否存在，存在就删除，删除完后再创建新路径
                apkFile = fileUtil.createFile(saveFileName);
                FileOutputStream outStream = new FileOutputStream(apkFile);
                int count = 0;
                byte buf[] = new byte[1024];
                do {
                    int numread = ins.read(buf);
                    count += numread;
                    progress = (int) (((float) count / length) * 100);
                    // 下载进度
                    handler.sendEmptyMessage(DOWN_UPDATE);
                    if (numread <= 0) {
                        handler.sendEmptyMessage(DOWN_OVER);
                        break;
                    }
                    outStream.write(buf, 0, numread);

                } while (!interceptFlag);// 点击取消的时候，取消下载
                outStream.close();
                ins.close();
            } catch (Exception e) {

            }
        }
    };

}
